package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.exception.CustomException;
import com.heima.feign.article.ArticleFeignClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.wemedia.context.BaseContext;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.pojos.WmNews;
import com.heima.wemedia.pojos.WmUser;
import com.heima.wemedia.service.WmStatisticsService;
import com.heima.wemedia.vos.WmNewsStatisticsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WmStatisticsServiceImpl implements WmStatisticsService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private ArticleFeignClient articleFeignClient;

    /**
     * 图文数据统计 上方4个数据的相关统计
     *
     * @param beginDateStr 开始时间
     * @param endDateStr   结束时间
     * @return 返回结果 将点赞量 收藏量 发布量放入map中
     */
    @Override
    public Map<String, Integer> newsDimension(String beginDateStr, String endDateStr) {
        //校验参数
        if (beginDateStr == null || beginDateStr == "" ||
                endDateStr == null || endDateStr == "") {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //校验是否登录
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //解析日期
        //解析日期型字符串 例如:"2024-05-01"==>转为Date类型
        Date beginDate = null;
        Date endDate = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            beginDate = sdf.parse(beginDateStr);
            endDate = sdf.parse(endDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Integer likesNum = null;
        Integer collectNum = null;
        //统计点赞量
        //统计收藏量
        WmUser wmUser = getWmUser(userId);
        if (wmUser == null) {
            return null;
        }
        Integer authorId = wmUser.getApUserId();
        ResponseResult<Map<String, Integer>> statistics = articleFeignClient.statistics(authorId, beginDate, endDate);
        if (statistics.getCode() != AppHttpCodeEnum.SUCCESS.getCode()) {
            throw new CustomException(AppHttpCodeEnum.CALL_INTERFACE_FAIL);
        }
        Map<String, Integer> data = statistics.getData();
        if (data != null) {
            likesNum = data.get("likesNum");
            collectNum = data.get("collectNum");
        }
        //统计发布量
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNews::getUserId, BaseContext.getCurrentId().intValue())
                .eq(WmNews::getEnable, 1)
                .ge(WmNews::getPublishTime, beginDate)
                .le(WmNews::getPublishTime, endDate);
        Integer publishNum = wmNewsMapper.selectCount(wrapper);

        HashMap<String, Integer> rsData = new HashMap<>();
        rsData.put("likesNum", likesNum);
        rsData.put("collectNum", collectNum);
        rsData.put("publishNum", publishNum);
        return rsData;
    }

    /**
     * 图文数据统计 下方数据分页查询
     *
     * @param beginDateStr 开始时间
     * @param endDateStr   结束时间
     * @param page         页码
     * @param size         每页显示条数
     * @return 返回结果
     */
    @Override
    public Page<WmNewsStatisticsVo> newPage(String beginDateStr, String endDateStr, Integer page, Integer size) {
        //校验参数
        if (beginDateStr == null || beginDateStr == "" ||
                endDateStr == null || endDateStr == "" ||
                page == null ||
                size == null
        ) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //校验是否登录
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //分页查询-app端文章信息
        //解析日期型字符串 例如:"2024-05-01"==>转为Date类型
        Date beginDate = null;
        Date endDate = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            beginDate = sdf.parse(beginDateStr);
            endDate = sdf.parse(endDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        WmUser wmUser = getWmUser(userId);
        if (wmUser == null) {
            return null;
        }
        Integer apUserId = wmUser.getApUserId();
        ResponseResult<Page<WmNewsStatisticsVo>> result = articleFeignClient.articlePage(beginDate, endDate, page, size, apUserId);
        if (result.getCode() != AppHttpCodeEnum.SUCCESS.getCode()) {
            throw new CustomException(AppHttpCodeEnum.CALL_INTERFACE_FAIL);
        }
        Page<WmNewsStatisticsVo> wmNewsStatisticsVoPage = result.getData();

        return wmNewsStatisticsVoPage;
    }

    /**
     * 获取自媒体用户信息
     *
     * @param userId 用户id
     * @return 返回结果
     */
    private WmUser getWmUser(Long userId) {
        LambdaQueryWrapper<WmUser> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(WmUser::getId, userId.intValue());
        WmUser wmUser = wmUserMapper.selectOne(userWrapper);
        return wmUser;
    }
}
